package org.kaer.election.ui;

import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

import org.kaer.election.R;
import org.kaer.election.fragment.BaseFragment;
import org.kaer.election.fragment.SearchServerFragment;
import org.kaer.election.utils.ActivityUtils;
import org.kaer.election.utils.LogUtils;

/**
 * Created by lizj on 2016/7/6.
 */
public class MainActivity extends BaseActivity {
    private long lastClick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        //避免重复添加Fragment
        System.out.println("MainActivity onCreate");
        if (null == getSupportFragmentManager().getFragments()) {
            LogUtils.e("getSupportFragmentManager().getFragments()==null");
            BaseFragment firstFragment = SearchServerFragment.newInstance();
            if (null != firstFragment) {
                addFragment(firstFragment);
            }
        } else {
            LogUtils.e("getSupportFragmentManager().getFragments()!=null");
        }
        initWidget();
    }

    private void initWidget() {
        initCommonBg();
    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected int getFragmentContentId() {
        return R.id.content;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                if (System.currentTimeMillis() - lastClick < 2000) {
                    if (mExampleClient.getConnectState() == mExampleClient.STATE_CONNECTED)
                        mExampleClient.disconnectServer();
                    ActivityUtils.finish();
                    System.exit(0);
                } else {
                    lastClick = System.currentTimeMillis();
                    Toast.makeText(MainActivity.this, "再点击一次退出", Toast.LENGTH_SHORT).show();
                }
                return true;
            } else
                return super.onKeyDown(keyCode, event);

        }
        return super.onKeyDown(keyCode, event);
    }
}
